<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/16
 * Time: 14:28
 */

namespace iBrand\Shop\Server\Http\Controllers;


use iBrand\Component\Point\Model\Point;
use iBrand\Component\Point\Repository\PointRepository;
use iBrand\Component\User\Models\User;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Repositories\UserShopRepository;

class PointController extends Controller
{

    protected $userShopRepository;
    protected $pointRepository;

    public function __construct(PointRepository $pointRepository
        , UserShopRepository $userShopRepository
    )
    {

        $this->userShopRepository = $userShopRepository;
        $this->pointRepository = $pointRepository;
    }

    /**
     * 店长操作积分基础信息
     * @return \Dingo\Api\Http\Response
     */
    public function opPointBase()
    {
        $clerk = auth('clerk')->user();

        if (!$user_id = request('user_id')) {
            return $this->api([], false, 400, '用户不存在');
        }

        if (!$clerk->shops->is_clerk_owner) {
            return $this->api([], false, 400, '无权限操作');
        }

        /*if (!$user = $this->userShopRepository->getUserInfoByShopId($clerk->shop_id, $user_id)) {
            return $this->api([], false, 400, '该会员非本门店会员');
        }*/

        $user = User::with('card')->with('shop')->find($user_id);

        $point = $this->pointRepository->getSumPointValid($user_id);

        $option = config('o2o.shop_owner_op_rule.point');
        $type = [];
        $i = 0;
        foreach ($option as $key => $item) {
            $type[$i]['name'] = $key;
            $type[$i]['value'] = $item;
            $i++;
        }

        return $this->api(['user' => $user, 'point' => $point, 'option' => $type]);
    }

    public function handlePoint()
    {
        $clerk = auth('clerk')->user();
        if (!$user_id = request('user_id')) {
            return $this->api([], false, 400, '用户不存在');
        }

        if (!$clerk->shops->is_clerk_owner) {
            return $this->api([], false, 400, '无权限操作');
        }

        /*if (!$user = $this->userShopRepository->getUserInfoByShopId($clerk->shop_id, $user_id)) {
            return $this->api([], false, 400, '该会员非本门店会员');
        }*/
        if (!$type = request('type') OR !$value = request('value') OR !$user_id = request('user_id')) {
            return $this->api([], false, 400, '请完善操作信息');
        }


        $note = config('o2o.shop_owner_op_rule.point_note')[$type] . request('note');

        if ($type == 'clerk_point_consumption' OR $type == 'clerk_point_other') {
            $value = -$value;
        }

        $point = Point::create([
            'user_id' => $user_id,
            'action' => 'clerk_action',
            'note' => $note,
            'value' => $value,
            'valid_time' => 0,
            'status' => 1]);
        event('point.change', $user_id);

        return $this->api(['point' => $point]);

    }
}